package com.demiroot.server.pages;

import java.util.Calendar;

import com.demiroot.server.HTTPResponse;
import com.demiroot.server.HTTPResquest;
import com.demiroot.server.HeaderData;
import com.demiroot.server.Server;
import com.demiroot.server.ServerSession;


public abstract class AuthenticatedPage implements Page {
	
	@Override
	public final HTTPResponse getPage(HTTPResquest request) {
		int authStatus = auth(request);
		if (authStatus == 0) {
			return getPageAuthed(request);
		}
		return getForbidenResponse(authStatus);
	}
	
	private HTTPResponse getForbidenResponse(int code) {
		String err;
		if (code == 1) {
			err = "Session Expired";
		} else if (code == 2) {
			err = "You need to login";
		} else if (code == 3) {
			err = "You don't have privledges to do that, stop trying";
		} else if (code == 4) {
			err = "Bad IP check, please login again";
		} else {
			err = "I don't know, somethings broken, try again?";
		}
		
		return new JavaPageResponse("<title>Error</title>" +
				"<br>Error: " + err+  "<br><a href=\"login\">Login</a>"); 
	}

	private int auth(HTTPResquest request) {
		String sessionId = request.getHeader().getCookieValue("session");
		if (sessionId == null) {
			return 2;
		}
		ServerSession ss = request.getServer().getSession(sessionId);
		if (ss == null || ss.getExpiry().before(Calendar.getInstance())) {
			return 1;
		}
		
		request.setSession(ss);
		
		//they have the right session cookie, the session
		//has not timed out.
		return 0;
	}
	
	public abstract HTTPResponse getPageAuthed(HTTPResquest request);
	
	public abstract int getPageLevel();
}
